package fr.dauphine.bookstore.backoffice.book;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanPropertyValueEqualsPredicate;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.hibernate.Session;

import fr.dauphine.bookstore.commun.MessagesUtil;
import fr.dauphine.bookstore.hibernate.HibernateUtil;
import fr.dauphine.bookstore.modele.Book;

/**
 * Upload d'une photo d'un livre.
 */
public final class UploadPhotoServlet extends HttpServlet {

	/**
	 * Serial version UID.
	 */
	private static final long serialVersionUID = 6691764298927858547L;

	/**
	 * Pour la conversion en Ko.
	 */
	private static final int SIZE_CONVERT = 1024;

	/**
	 * Traite la methode POST.
	 * 
	 * @param request
	 *            Requete
	 * @param response
	 *            Reponse
	 * @throws ServletException
	 *             Erreur de servlet
	 * @throws IOException
	 *             Erreur d'entree/sortie
	 */
	protected void doPost(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
		Long id = Long.valueOf(request.getParameter("id"));

		ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());

		FileItem photo = null;
		try {
			photo = (FileItem) CollectionUtils.find(upload.parseRequest(request), new BeanPropertyValueEqualsPredicate("fieldName", "photo"));

		} catch (FileUploadException e) {
			throw new ServletException(e.getMessage());
		}

		if (photo == null) {
			MessagesUtil.addMessage(request, MessagesUtil.ERROR, "La photo est obligatoire");

		} else if (!"image/jpeg".equals(photo.getContentType())) {
			MessagesUtil.addMessage(request, MessagesUtil.ERROR, "La photo doit etre un fichier JPEG");

		} else if (photo.getSize() > Book.PHOTO_MAX_SIZE) {
			MessagesUtil.addMessage(request, MessagesUtil.ERROR, "La photo ne doit pas depasser " + (Book.PHOTO_MAX_SIZE / SIZE_CONVERT) + " Ko");
		}

		if (MessagesUtil.isThereErrors(request)) {
			request.getRequestDispatcher("uploadPhoto.jsp").forward(request, response);

		} else {
			Session hSession = HibernateUtil.getSessionFactory().getCurrentSession();

			Book book = (Book) hSession.get(Book.class, id);
			book.setPhoto(photo.get());
			hSession.save(book);

			response.sendRedirect("books.jsp");
		}
	}
}
